import ajax from './ajax.js'

// 导出excel，csv;xlsx文件把,替换成\t
function exportToCsv(data, filename) {
  const csvContent = "data:text/csv;charset=utf-8," + data.map(row => row.join(",")).join("\n");
  const encodedUri = encodeURI(csvContent);
  const link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", filename);
  link.click();
}

const data = [
  ["Name", "Age", "City"],
  ["John", "30", "New York"],
  ["Jane", "25", "London"],
  ["Jim", "35", "Paris"]
];

exportToCsv(data, "output.csv");
/* eslint-disable */
function getTable(jsonData, title, fileName = '数据表', line1, line2) {
  // 列标题
  var count = 0
  for (var j in title) {
    count++
  }
  let str = `<th colspan="${count}" style="font-size: 20px;">${fileName}</th><tr style="font-size: 14px;">`
  if (line1) {
    for (let i of line1) {
      str += `<td rowspan=${i[1]} colspan=${i[2]}>${i[0]}</td>`
    }
    str += '</tr><tr style="font-size: 14px;">'
    for (let i of line2) {
      str += `<td>${i}</td>`
    }
  } else {
    for (var i in title) {
      str = str + '<td>' + title[i] + '</td>'
    }
  }
  str += '</tr>'
  // 循环遍历，每行加入tr标签，每个单元格加td标签
  for (let i = 0; i < jsonData.length; i++) {
    str += '<tr style="text-align: left;font-size: 14px;mso-number-format:\'@\'">'
    for (var item in title) {
      // 增加\t为了不让表格显示科学计数法或者其他格式
      if (jsonData[i][item] === undefined || jsonData[i][item] === null) {
        str += `<td>\t</td>`
      } else {
        str += `<td>${jsonData[i][item] + '\t'}</td>`
      }
    }
    str += '</tr>'
  }
  return str
}

/**
 * json数据转为Excel并下载
 * @param jsonData
 * jsonData = [
 {
      name: '路人甲',
      phone: '123456789',
      email: '000@123456.com'
    }
 ]
 * @param title 格式:{
        id: 'ID',
        name: '角色名称'
      }
 * @param fileName 默认文件名: '数据表'
 */
function jsonToExcel(jsonData, title, fileName = '数据表', line1, line2) {
  let str = getTable(...arguments)
  // Worksheet名
  const worksheet = 'Sheet1'
  const uri = 'data:application/vnd.ms-excel;base64,'

  // 下载的表格模板数据
  const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
  // 下载模板
  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = fileName
  a.click()
}

function printTable(jsonData, title, fileName = '数据表', line1, line2) {
  let str = getTable(...arguments)
  const template = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html>
      <head>
      <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
      <link href="/css/print.css" rel="stylesheet" type="text/css" media="screen,print" />
      <title>打印报表</title>
        </head><body><table>${str}</table></body></html>`
  // 打印模板
  const win = window.open('')
  win.document.write(template)
  win.print()
  setTimeout(function () {
    win.close();
  }, 200)
}

function getToday(offset = 0) {
  var date = (new Date()).getTime()
  date = date + 86400000 * offset
  date = new Date(date)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  return `${year}-${month}-${day}`
}

function getTime(time) {
  if (!time) return ''
  var date = new Date(time)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var h = date.getHours()
  var m = date.getMinutes()
  var s = date.getSeconds()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  h < 10 && (h = '0' + h)
  m < 10 && (m = '0' + m)
  s < 10 && (s = '0' + s)
  return `${year}-${month}-${day} ${h}:${m}:${s}`
}

function dateFormat(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString(),      // 秒
    "s+": date.getMilliseconds().toString()          // 毫秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    }
  }
  return fmt;
}

function utc2beijing(fmt, date) {
  let ret;

  var newDate = new Date(date - 8*60*60*1000); // subtract 3 hours.
  const opt = {
    "Y+": newDate.getFullYear().toString(),        // 年
    "m+": (newDate.getMonth() + 1).toString(),     // 月
    "d+": newDate.getDate().toString(),            // 日
    "H+": newDate.getHours().toString(),           // 时
    "M+": newDate.getMinutes().toString(),         // 分
    "S+": newDate.getSeconds().toString(),      // 秒
    "s+": newDate.getMilliseconds().toString()          // 毫秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    }
  }
  return fmt;
}

function numberToString(obj) {
  for (var i in obj) {
    if (typeof obj[i] === 'number') {
      obj[i] += ''
    }
  }
}

function nullToString(obj) {
  for (var j in obj) {
    if (obj[j] === null) {
      obj[j] = ''
    }
  }
}

function copyValue(oldVal, newVal) {
  for (var k in oldVal) {
    newVal[k] && (oldVal[k] = newVal[k])
  }
}

function download(url) {
  var a = document.createElement('a')
  a.download = 'download'
  a.href = url
  a.click()
}

function print(data) {
  console.log(JSON.stringify(data, null, 2))
}

async function getAllTableData(obj) {
  obj = JSON.parse(JSON.stringify(obj))
  obj.data[0].start = 0
  obj.data[0].limit = 999999
  return (await ajax(obj)).items
}

export default {
  getAllTableData,
  jsonToExcel,
  printTable,
  getToday,
  numberToString,
  nullToString,
  download,
  print,
  copyValue,
  getTime,
  dateFormat,
  utc2beijing
}
